# -*- coding: utf-8 -*-

from concurrent import futures
import grpc
from grpc_server import distinguish_pb2
from grpc_server import distinguish_pb2_grpc
import time
from distinguish import distinguish_factory
import os

_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = '[::]'
_PORT = os.getenv('DISTINGUISH_SERVER_PORT', default='8080')


class DistinguishServicer(distinguish_pb2_grpc.DistinguishServicer):
    def Distinguish(self, request, context):
        if request.category == distinguish_pb2.Image.DATA1:
            category = 'data1'
        elif request.category == distinguish_pb2.Image.DATA2:
            category = 'data2'
        elif request.category == distinguish_pb2.Image.DATA3:
            category = 'data3'
        elif request.category == distinguish_pb2.Image.DATA4:
            category = 'data4'
        else:
            category = 'data1'

        distinguish = distinguish_factory.get(category)
        yzm = distinguish.distinguish(request.data)
        return distinguish_pb2.Yzm(yzm=yzm)


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    distinguish_pb2_grpc.add_DistinguishServicer_to_server(
        DistinguishServicer(), server)
    server.add_insecure_port(_HOST + ':' + _PORT)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == '__main__':
    serve()
